package com.sky.service.impl;

import com.sky.dto.DataOverViewQueryDTO;
import com.sky.dto.GoodsSalesDTO;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ServiceProviderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 报表服务实现类
 */
@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ServiceProviderMapper serviceProviderMapper;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<BigDecimal> turnoverList = new ArrayList<>();

        // 遍历日期范围
        for (LocalDate date = begin; !date.isAfter(end); date = date.plusDays(1)) {
            dateList.add(date);
            // 查询该日期的营业额
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            BigDecimal turnover = orderMapper.getTurnoverByTimeRange(beginTime, endTime);
            turnoverList.add(turnover != null ? turnover : BigDecimal.ZERO);
        }

        // 组装数据
        String dateListStr = dateList.stream()
                .map(LocalDate::toString)
                .collect(Collectors.joining(","));
        String turnoverListStr = turnoverList.stream()
                .map(BigDecimal::toString)
                .collect(Collectors.joining(","));

        return TurnoverReportVO.builder()
                .dateList(dateListStr)
                .turnoverList(turnoverListStr)
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();

        // 遍历日期范围
        for (LocalDate date = begin; !date.isAfter(end); date = date.plusDays(1)) {
            dateList.add(date);
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            // 查询该日期的总用户数
            Integer totalUser = userMapper.getTotalUserByTimeRange(beginTime, endTime);
            totalUserList.add(totalUser != null ? totalUser : 0);

            // 查询该日期的新增用户数
            Integer newUser = userMapper.getNewUserByTimeRange(beginTime, endTime);
            newUserList.add(newUser != null ? newUser : 0);
        }

        // 组装数据
        String dateListStr = dateList.stream()
                .map(LocalDate::toString)
                .collect(Collectors.joining(","));
        String totalUserListStr = totalUserList.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(","));
        String newUserListStr = newUserList.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(","));

        return UserReportVO.builder()
                .dateList(dateListStr)
                .totalUserList(totalUserListStr)
                .newUserList(newUserListStr)
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();

        // 遍历日期范围
        for (LocalDate date = begin; !date.isAfter(end); date = date.plusDays(1)) {
            dateList.add(date);
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            // 查询该日期的订单总数
            Integer orderCount = orderMapper.getOrderCountByTimeRange(beginTime, endTime);
            orderCountList.add(orderCount != null ? orderCount : 0);

            // 查询该日期的有效订单数
            Integer validOrderCount = orderMapper.getValidOrderCountByTimeRange(beginTime, endTime);
            validOrderCountList.add(validOrderCount != null ? validOrderCount : 0);
        }

        // 组装数据
        String dateListStr = dateList.stream()
                .map(LocalDate::toString)
                .collect(Collectors.joining(","));
        String orderCountListStr = orderCountList.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(","));
        String validOrderCountListStr = validOrderCountList.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(","));

        return OrderReportVO.builder()
                .dateList(dateListStr)
                .orderCountList(orderCountListStr)
                .validOrderCountList(validOrderCountListStr)
                .build();
    }

    /**
     * 销量排名TOP10
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        // 查询服务人员销量TOP10
        List<GoodsSalesDTO> top10List = serviceProviderMapper.getSalesTop10(beginTime, endTime);

        // 组装数据
        String nameList = top10List.stream()
                .map(GoodsSalesDTO::getName)
                .collect(Collectors.joining(","));
        String numberList = top10List.stream()
                .map(GoodsSalesDTO::getNumber)
                .map(String::valueOf)
                .collect(Collectors.joining(","));

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 数据概览
     * @param dataOverViewQueryDTO
     * @return
     */
    public BusinessDataVO getBusinessData(DataOverViewQueryDTO dataOverViewQueryDTO) {
        LocalDateTime begin = LocalDateTime.of(dataOverViewQueryDTO.getDate(), LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dataOverViewQueryDTO.getDate(), LocalTime.MAX);

        // 查询营业额
        BigDecimal turnover = orderMapper.getTurnoverByTimeRange(begin, end);
        turnover = turnover != null ? turnover : BigDecimal.ZERO;

        // 查询有效订单数
        Integer validOrderCount = orderMapper.getValidOrderCountByTimeRange(begin, end);
        validOrderCount = validOrderCount != null ? validOrderCount : 0;

        // 查询订单总数
        Integer orderCount = orderMapper.getOrderCountByTimeRange(begin, end);
        orderCount = orderCount != null ? orderCount : 0;

        // 计算订单完成率
        Double orderCompletionRate = 0.0;
        if (orderCount > 0) {
            orderCompletionRate = (double) validOrderCount / orderCount * 100;
        }

        // 计算平均客单价
        Double unitPrice = 0.0;
        if (validOrderCount > 0) {
            unitPrice = turnover.doubleValue() / validOrderCount;
        }

        // 查询新增用户数
        Integer newUsers = userMapper.getNewUserByTimeRange(begin, end);
        newUsers = newUsers != null ? newUsers : 0;

        return BusinessDataVO.builder()
                .turnover(turnover.doubleValue())
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .unitPrice(unitPrice)
                .newUsers(newUsers)
                .build();
    }
} 